using System.Text.Json;
using IMServer.Services;

namespace IMServer.Endpoints
{
    public static class MessageEndpoint
    {
        public static RouteGroupBuilder MapMessageApi(this RouteGroupBuilder group)
        {
            // 获取用户所有未读的消息，并标记为已读，仅用于登录时
            group.MapPost("/unread", async (HttpContext context) =>
            {
                try
                {
                    using var document = await JsonDocument.ParseAsync(context.Request.Body);
                    if (!document.RootElement.TryGetProperty("UserId", out var userIdElement))
                    {
                        return Results.Json(new
                        {
                            Code = "1101",
                            Message = "用户ID不能为空"
                        });
                    }

                    string userId = userIdElement.GetString() ?? string.Empty;
                    if (string.IsNullOrEmpty(userId))
                    {
                        return Results.Json(new
                        {
                            Code = "1101",
                            Message = "用户ID不能为空"
                        });
                    }

                    // 获取未读消息
                    var (unreadMessages, unreadCount) = await MessageBoxDbService.Instance
                        .GetUnreadMessagesAsync(userId);

                    // 按时间顺序排序消息
                    var orderedMessages = unreadMessages
                        .OrderBy(m => m.Timestamp)
                        .ToList();

                    // 通过 WebSocket 按顺序发送每条未读消息
                    foreach (var message in orderedMessages)
                    {
                        await WebSocketManager.Instance.SendMessageToUserAsync(
                            userId,
                            message.ToJson()
                        );
                        await Task.Delay(50);  // 50ms 延迟
                    }
                    
                    // 获取未处理的请求类消息
                    var pendingRequests = await PendingRequestBoxesDbService.Instance
                        .GetAllPendingRequestsAsync(userId);
                    
                    // 通过 WebSocket 发送未处理的请求类消息
                    foreach (var request in pendingRequests)
                    {
                        await WebSocketManager.Instance.SendMessageToUserAsync(
                            userId,
                            request.ToJson()
                        );
                        await Task.Delay(50);
                    }
                    
                    return Results.Json(new
                    {
                        Code = "0000",
                        Message = "获取成功",
                        Data = new
                        {
                            UnreadCount = unreadCount,
                            Messages = orderedMessages,
                            PendingRequests = pendingRequests
                        }
                    });
                }
                catch(Exception ex)
                {
                    return Results.Json(new
                    {
                        Code = "5000",
                        Message = $"服务器错误: {ex.Message}"
                    });
                }
            });
            return group;
        }
    }
}

